import React from 'react'
import DisplayError from './DisplayError'
import { useController } from 'react-hook-form'
import styles from './common.module.scss'
import classNames from 'classnames';

interface IProps {
    label?: string;
    errors?: string;
    type?: string;
    name: string;
    control: any;
    direction?: "ltr" | "rtl";
    placeholder?: string;
}

const TextField = ({ label, errors, name, type = 'text', control, direction, inputProps }: IProps) => {

    const { field } = useController({ name, control, rules: { required: true } })

    const onChangeHandler = (e: any) => {
        const inputValue = e.target.value

        if (type === 'number' && inputValue.length !== 0) {
            field.onChange(parseInt(inputValue))
        } else {
            field.onChange(inputValue)
        }
    }


    return (
        <div className={classNames(styles.text_field, '!w-[311px]', 'm-auto')}>
            {label && (
                <label className={styles.text_field__label} htmlFor={name}>
                    {label}
                </label>
            )}
            <input
                style={{ direction: `${direction === 'rtl' ? 'rtl' : 'ltr'}` }}
                className={styles.text_field__input}
                id={name}
                value={field?.value}
                name={field.name}
                onBlur={field.onBlur}
                onChange={onChangeHandler}
                ref={field.ref}
                {...inputProps}
            />

            <DisplayError errors={errors} />
        </div>
    )

}

export default TextField